package cn.yangyumanage.adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.recyclerview.widget.RecyclerView;

import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.wang.avi.AVLoadingIndicatorView;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import cn.yangyumanage.R;
import cn.yangyumanage.application.DataApplication;
import cn.yangyumanage.bean.LeaveMessage;
import cn.yangyumanage.bean.LeaveMessageWithUserInfo;
import cn.yangyumanage.callback.DataCallBack;
import cn.yangyumanage.http.HttpClient;
import cn.yangyumanage.model.LeaveMessageHttpModel;
import cn.yangyumanage.util.ToastUtil;

public class LeaveMessageWithUserInfoRvAdapter extends RecyclerView.Adapter<LeaveMessageWithUserInfoRvAdapter.MyViewHolder> {

    private final List<LeaveMessageWithUserInfo> leaveMessages = new ArrayList<>();
    private LeaveMessageHttpModel httpModel = new LeaveMessageHttpModel();
    private Context context;
    private ColorStateList blueColorStateList;

    public void setContext(Context context) {
        this.context = context;
        blueColorStateList = AppCompatResources.getColorStateList(context, R.color.blue);
    }

    public void setData(List<LeaveMessageWithUserInfo> leaveMessagesData) {
        int startPosition = leaveMessages.size();
        leaveMessages.addAll(leaveMessagesData);
        notifyItemRangeInserted(startPosition, leaveMessagesData.size());
    }

    @SuppressLint("NotifyDataSetChanged")
    public void clearAllData() {
        leaveMessages.clear();
        notifyDataSetChanged(); // 通知RecyclerView更新整个列表
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.leave_message_rv_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
        LeaveMessageWithUserInfo leaveMessage = leaveMessages.get(position);
        holder.tv_content.setText(leaveMessage.getContent());
        String dateString = leaveMessage.getLeaveTime().toString();
        String leaveTimeString = dateString.substring(0, dateString.length() - 2);
        holder.tv_leave_time.setText("留言于 " + leaveTimeString);
        holder.tv_nickname.setText(" - by " + leaveMessage.getNickname());
        String reply = leaveMessage.getReply();
        Timestamp replyTime = leaveMessage.getReplyTime();
        if (reply != null && replyTime != null) {
            holder.ll_replay.setVisibility(View.VISIBLE);
            holder.tv_reply_content.setText(reply);
            String replyDateString = replyTime.toString();
            String replyTimeString = replyDateString.substring(0, replyDateString.length() - 2);
            holder.tv_reply_time.setText("回复于 " + replyTimeString);
            holder.tv_reply_nickname.setText(" - by 管理员");
        } else {
            holder.ll_replay.setVisibility(View.GONE);
        }
        holder.srl_item.setLockDrag(true);
        holder.srl_item.close(true);
        holder.ll_item.setOnClickListener(new View.OnClickListener() {
            boolean flag = false;

            @Override
            public void onClick(View v) {

                if (!flag) {
                    holder.srl_item.open(true);
                    flag = true;
                } else {
                    holder.srl_item.close(true);
                    flag = false;
                }
            }
        });
        holder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建提醒对话框的构建器
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                //设置对话框的内容文本
                builder.setMessage("真的要删除该留言吗？");
                //设置对话框的肯定按钮文本及其点击监听器
                builder.setPositiveButton("取消", null);
                //设置对话框的否定按钮文本及其点击监听器
                builder.setNegativeButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteLeaveMessageById(leaveMessage.getId(), position);
                    }
                });

                //根据建造器构建提醒对话框对象
                AlertDialog dialog = builder.create();
                //显示提醒对话框
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED);
            }
        });
        int state = leaveMessage.getState();
        if (state == 0) {
            holder.tv_pass.setVisibility(View.VISIBLE);
            holder.tv_pass.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog("通过", blueColorStateList, leaveMessage, position, "pass", 1);
                }
            });
            holder.tv_reject.setVisibility(View.VISIBLE);
            holder.tv_reject.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog("驳回", blueColorStateList, leaveMessage, position, "reject", 2);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return leaveMessages.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private final TextView tv_content;
        private final TextView tv_leave_time;
        private final TextView tv_nickname;
        private final TextView tv_reply_content;
        private final TextView tv_reply_time;
        private final TextView tv_reply_nickname;
        private final LinearLayout ll_replay;
        private final SwipeRevealLayout srl_item;
        private final LinearLayout ll_item;
        private final TextView tv_delete;
        private final TextView tv_reject;
        private final TextView tv_pass;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_content = itemView.findViewById(R.id.tv_content);
            tv_leave_time = itemView.findViewById(R.id.tv_leave_time);
            tv_nickname = itemView.findViewById(R.id.tv_nickname);
            tv_reply_content = itemView.findViewById(R.id.tv_reply_content);
            tv_reply_time = itemView.findViewById(R.id.tv_reply_time);
            tv_reply_nickname = itemView.findViewById(R.id.tv_reply_nickname);
            ll_replay = itemView.findViewById(R.id.ll_replay);
            srl_item = itemView.findViewById(R.id.srl_item);
            ll_item = itemView.findViewById(R.id.ll_item);
            tv_delete = itemView.findViewById(R.id.tv_delete);
            tv_reject = itemView.findViewById(R.id.tv_reject);
            tv_pass = itemView.findViewById(R.id.tv_pass);
        }
    }

    //根据留言id删除留言
    private void deleteLeaveMessageById(Integer id, int position) {
        httpModel.deleteLeaveMessageById(id, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (flag) {
                            ToastUtil.show(context, "删除成功");
                            leaveMessages.remove(position);
                            notifyDataSetChanged();
                        } else {
                            ToastUtil.show(context, "删除失败");
                        }
                    }
                });
            }
        });
    }

    //通过id更新留言数据
    private void updateLeaveMessageById(LeaveMessageWithUserInfo leaveMessage, int position, AlertDialog dialog, String action) {
        httpModel.updateLeaveMessageById(leaveMessage, new DataCallBack() {
            @Override
            public void getData(Object data) {
                Boolean flag = (Boolean) data;
                HttpClient.handler.post(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        switch (action) {
                            case "reject":
                                if (flag) {
                                    dialog.dismiss();
                                    ToastUtil.show(context, "驳回成功");
                                    DataApplication.notPassLeaveMessageFlag=false;
                                    leaveMessages.remove(position);
                                    notifyDataSetChanged();
                                } else {
                                    ToastUtil.show(context, "驳回失败");
                                }
                                break;
                            case "pass":
                                if (flag) {
                                    dialog.dismiss();
                                    ToastUtil.show(context, "通过成功");
                                    DataApplication.passLeaveMessageFlag=false;
                                    leaveMessages.remove(position);
                                    notifyDataSetChanged();
                                } else {
                                    ToastUtil.show(context, "通过失败");
                                }
                                break;
                        }
                    }
                });
            }
        });
    }

    private void showDialog(String negativeButtonText, ColorStateList colorStateList, LeaveMessageWithUserInfo leaveMessage, int position, String action, Integer state) {
        View dialogView = View.inflate(context, R.layout.leavemessage_dialog_layout, null);
        EditText et_reply = dialogView.findViewById(R.id.et_reply);
        AVLoadingIndicatorView aiv_leave_message = dialogView.findViewById(R.id.aiv_leave_message);
        //创建提醒对话框的构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        //设置对话框的内容文本
        builder.setMessage("真的要" + negativeButtonText + "该留言吗？");
        //设置对话框的肯定按钮文本及其点击监听器
        builder.setPositiveButton("取消", null);
        //设置对话框的否定按钮文本及其点击监听器
        builder.setNegativeButton(negativeButtonText, null);

        //根据建造器构建提醒对话框对象
        AlertDialog dialog = builder.create();
        dialog.setView(dialogView);
        // 设置其他区域不关闭窗口
        dialog.setCanceledOnTouchOutside(false);
        //显示提醒对话框
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(colorStateList);
        // 手动处理确认按钮的点击事件
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String reply = et_reply.getText().toString();
                LeaveMessageWithUserInfo updateLeaveMessage =new LeaveMessageWithUserInfo();
                if (!reply.equals("")) {
                    updateLeaveMessage.setReply(reply);
                }
                updateLeaveMessage.setId(leaveMessage.getId());
                updateLeaveMessage.setState(state);
                updateLeaveMessage.setContent(leaveMessage.getContent());
                updateLeaveMessage.setEmail(leaveMessage.getEmail());
                updateLeaveMessage.setNickname(leaveMessage.getNickname());
                aiv_leave_message.smoothToShow();
                updateLeaveMessageById(updateLeaveMessage, position, dialog, action);
            }
        });
    }
}
